import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Upload,
  Modal,
  Form,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  message,
} from 'antd';
import {
  PlusOutlined,
  UploadOutlined,
  SearchOutlined,
  EyeOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons';

const { Title } = Typography;
const { Search } = Input;
const { Option } = Select;

const SheetMusic = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filterCategory, setFilterCategory] = useState('all');

  // 模拟数据
  const [dataSource, setDataSource] = useState([
    {
      key: '1',
      title: '夜空中最亮的星',
      artist: '逃跑计划',
      category: '流行',
      difficulty: '中等',
      uploadDate: '2024-01-15',
      fileSize: '2.3MB',
      downloads: 45,
      status: 'active',
    },
    {
      key: '2',
      title: '海阔天空',
      artist: 'Beyond',
      category: '摇滚',
      difficulty: '困难',
      uploadDate: '2024-01-10',
      fileSize: '3.1MB',
      downloads: 78,
      status: 'active',
    },
    {
      key: '3',
      title: '光辉岁月',
      artist: 'Beyond',
      category: '摇滚',
      difficulty: '中等',
      uploadDate: '2024-01-08',
      fileSize: '2.8MB',
      downloads: 62,
      status: 'active',
    },
    {
      key: '4',
      title: '童话',
      artist: '光良',
      category: '流行',
      difficulty: '简单',
      uploadDate: '2024-01-05',
      fileSize: '1.9MB',
      downloads: 89,
      status: 'active',
    },
  ]);

  const categories = ['流行', '摇滚', '民谣', '爵士', '古典', '电子'];
  const difficulties = ['简单', '中等', '困难'];

  const columns = [
    {
      title: '歌曲名称',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '艺术家',
      dataIndex: 'artist',
      key: 'artist',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => <Tag color="blue">{category}</Tag>,
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      render: (difficulty) => {
        const colorMap = {
          '简单': 'green',
          '中等': 'orange',
          '困难': 'red',
        };
        return <Tag color={colorMap[difficulty]}>{difficulty}</Tag>;
      },
    },
    {
      title: '上传日期',
      dataIndex: 'uploadDate',
      key: 'uploadDate',
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
    },
    {
      title: '下载次数',
      dataIndex: 'downloads',
      key: 'downloads',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
          >
            下载
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleView = (record) => {
    message.info(`查看乐谱: ${record.title}`);
  };

  const handleDownload = (record) => {
    message.success(`开始下载: ${record.title}`);
  };

  const handleEdit = (record) => {
    setEditingRecord(record);
    setIsModalVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除乐谱 "${record.title}" 吗？`,
      onOk() {
        setDataSource(dataSource.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };

  const handleAdd = () => {
    setEditingRecord(null);
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    setIsModalVisible(false);
    setEditingRecord(null);
    message.success(editingRecord ? '更新成功' : '添加成功');
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setEditingRecord(null);
  };

  const filteredData = dataSource.filter(item => {
    const matchesSearch = item.title.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.artist.toLowerCase().includes(searchText.toLowerCase());
    const matchesCategory = filterCategory === 'all' || item.category === filterCategory;
    return matchesSearch && matchesCategory;
  });

  return (
    <div>
      <Title level={2}>乐谱管理</Title>

      {/* 搜索和过滤 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={12} md={8}>
            <Search
              placeholder="搜索歌曲名称或艺术家"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="选择分类"
              style={{ width: '100%' }}
              value={filterCategory}
              onChange={setFilterCategory}
            >
              <Option value="all">全部分类</Option>
              {categories.map(category => (
                <Option key={category} value={category}>{category}</Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={24} md={10}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加乐谱
              </Button>
              <Upload
                name="file"
                action="/api/upload"
                onChange={(info) => {
                  if (info.file.status === 'done') {
                    message.success(`${info.file.name} 上传成功`);
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败`);
                  }
                }}
              >
                <Button icon={<UploadOutlined />}>批量上传</Button>
              </Upload>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 乐谱列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredData}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加/编辑乐谱模态框 */}
      <Modal
        title={editingRecord ? '编辑乐谱' : '添加乐谱'}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
      >
        <Form
          layout="vertical"
          initialValues={editingRecord || {}}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="歌曲名称"
                name="title"
                rules={[{ required: true, message: '请输入歌曲名称' }]}
              >
                <Input placeholder="请输入歌曲名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="艺术家"
                name="artist"
                rules={[{ required: true, message: '请输入艺术家' }]}
              >
                <Input placeholder="请输入艺术家" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="分类"
                name="category"
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  {categories.map(category => (
                    <Option key={category} value={category}>{category}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="难度"
                name="difficulty"
                rules={[{ required: true, message: '请选择难度' }]}
              >
                <Select placeholder="请选择难度">
                  {difficulties.map(difficulty => (
                    <Option key={difficulty} value={difficulty}>{difficulty}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="乐谱文件"
            name="file"
          >
            <Upload.Dragger
              name="file"
              multiple={false}
              action="/api/upload"
              accept=".pdf,.jpg,.png,.gif"
            >
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持 PDF、JPG、PNG、GIF 格式
              </p>
            </Upload.Dragger>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SheetMusic; 